package com.graduation_design.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation_design.common.dto.LoginDto;
import com.graduation_design.common.lang.Const;
import com.graduation_design.entity.AppUser;
import com.graduation_design.service.AppUserService;
import com.graduation_design.mapper.AppUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
* @author 从南
* @description 针对表【app_user(用户表)】的数据库操作Service实现
* @createDate 2024-02-16 18:15:59
*/
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser>
    implements AppUserService{

    @Resource
    HttpSession httpSession;

    /**
     * 用户登录
     */
    @Override
    public AppUser login(LoginDto loginDto) {

        AppUser appUser = this.getOne(new QueryWrapper<AppUser>()
                .eq("username", loginDto.getUsername())
        );

        // 校验用户名和密码
        Assert.notNull(appUser, "用户名不存在");
        Assert.isTrue(appUser.getPassword().equals(SecureUtil.md5(loginDto.getPassword())), "用户名或密码错误");

        // 更新最后登录时间
        appUser.setLastLogin(LocalDateTime.now());
        this.updateById(appUser);

        return appUser;
    }

    /**
     * 获取被注入到会话session中的userId
     */
    @Override
    public long getCurrentUserId() {
        Long userId = (Long) httpSession.getAttribute(Const.USER_KEY);
        return userId == null ? -1 : userId;
    }

    /**
     * 获取当前用户信息
     */
    @Override
    public AppUser getCurrentUser() {
        Long userId = getCurrentUserId();
        return userId == null ? null : this.getById(userId);
    }
}




